﻿using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;

namespace Kevin.SLUserControlLibrary
{
    public class ColorItem : ButtonBase
    {
        public static readonly DependencyProperty IsCheckedProperty = DependencyProperty
            .Register("IsChecked", typeof(bool), typeof(ColorItem),
            new PropertyMetadata(new PropertyChangedCallback(ColorItem.OnIsCheckedChanged)));

        public static readonly DependencyProperty DisplayColorProperty = DependencyProperty
          .Register("DisplayColor", typeof(SolidColorBrush), typeof(ColorItem), null);

        public bool IsChecked
        {
            get { return (bool)GetValue(ColorItem.IsCheckedProperty); }
            set { SetValue(ColorItem.IsCheckedProperty, value); }
        }

        public SolidColorBrush DisplayColor
        {
            get { return (SolidColorBrush)GetValue(ColorItem.DisplayColorProperty); }
            set { SetValue(ColorItem.DisplayColorProperty, value); }
        }

        public ColorItem()
        {
            this.DefaultStyleKey = typeof(ColorItem);
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
        }

        protected override void OnClick()
        {
            base.OnClick();
            this.IsChecked = true;
            this.ChangeVisualState(true);
        }


        protected override void OnMouseEnter(MouseEventArgs e)
        {
            base.OnMouseEnter(e);
            this.ChangeVisualState(true);
        }

        protected override void OnMouseLeave(MouseEventArgs e)
        {
            base.OnMouseLeave(e);
            this.ChangeVisualState(true);
        }

        private static void OnIsCheckedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ColorItem colorItem = (ColorItem)d;
            colorItem.ChangeVisualState(true);
        }

        private void ChangeVisualState(bool useTransitions)
        {
            if (!base.IsEnabled)
            {
                VisualStateManager.GoToState(this, "Disabled", useTransitions);
            }
            else if (this.IsChecked)
            {
                VisualStateManager.GoToState(this, "Checked", useTransitions);
            }
            else if (this.IsMouseOver)
            {
                VisualStateManager.GoToState(this, "MouseOver", useTransitions);
            }
            else
            {
                VisualStateManager.GoToState(this, "Normal", useTransitions);
            }

        }
    }
}
